<template>
  <div class="add-sign-in-wrap">
    <div class="tips-info">
      <h4>操作提示</h4>
      <ul>
        <li>众筹有开始和结束时间，在结束时间前达到目标值就算众筹成功，在结束时间点没有达到目标值就算众筹失败，钱退回。</li>
        <li>众筹需要设置总金额，总金额达到设定的比例就算众筹成功。</li>
        <li>众筹单价按阶梯来，比如前100个商品众筹单价为200元；101-200个商品众筹单价为220元；201个以上的商品众筹单价为240元。</li>
        <li>金额达到目标值也可以继续众筹，直到活动结束。</li>
      </ul>
    </div>

    <div class="sign-in-container">
      <div class="form-box">
        <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="140px"
        :status-icon="false"
        label-position="right"
        :disabled="disabled">
          <el-divider>基础设置</el-divider>
          <el-form-item label="活动名称" prop="name">
            <el-input size="medium" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="活动时间" prop="timeRange">
            <el-date-picker
              v-model="form.timeRange"
              size="medium"
              style="width: 400px"
              type="datetimerange"
              align="center"
              :editable="false"
              unlink-panels
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="timestamp"
              :default-time="[MixinDefaultTime, MixinDefaultTime]"
              :picker-options="{disabledDate(time) { return time.getTime()  <  (Date.now() - 8.64E7) }}">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="众筹总金额" prop="total_price">
            <el-input size="medium" v-model="form.total_price"></el-input>
          </el-form-item>
          <el-form-item label="众筹成功比例" prop="price_ratio">
            <el-input size="medium" v-model="form.price_ratio">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <el-form-item label="活动描述" prop="description">
            <el-input type="textarea" size="medium" v-model="form.description" clearable></el-input>
          </el-form-item>
          <el-divider>商品设置</el-divider>
          <el-form-item label="众筹商品">
            <en-table-layout
              toolbar
              pagination
              :tableData="goodsTableData">
              <div slot="toolbar" class="inner-toolbar">
                <div class="toolbar-btns" v-if="!disabled">
                  <el-button type="primary" @click="handlerSelectGoods" >选择商品</el-button>
                </div>
              </div>
              <template slot="table-columns">
                <el-table-column label="商品名称">
                  <template slot-scope="scope">
                    <a :href="isO2O ? 'javascript:void(0)' : `${MixinBuyerDomain}/goods/${scope.row.goods_id}`" :target="isO2O ? '' : '_blank'" style="color: #00a2d4;" v-html="scope.row.goods_name">{{ scope.row.goods_name }}</a>
                  </template>
                </el-table-column>
                <!-- 商品规格 -->
                <el-table-column label="规格">
                  <template slot-scope="scope">
                    <div class="sku-list">
                      <span v-if="scope.row.spec_list">{{ getSkuList(scope.row.spec_list) }}</span>
                      <span v-else>{{ getSkuList(scope.row.specs) }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="价格">
                  <template slot-scope="scope">
                      <span>{{ scope.row.price }}</span>
                  </template>
                </el-table-column>
              </template>
            </en-table-layout>
          </el-form-item>
          <el-divider>价格阶梯</el-divider>
          <el-form-item label="价格阶梯">
            <el-button v-if="!disabled" type="primary" @click="handleAddPriceStep" icon="el-icon-circle-plus-outline">新增阶梯</el-button>
            <el-table :data="form.price_step_list" :header-cell-style="{ textAlign: 'center' }">
              <el-table-column label="序号" width="50" align="center">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="门槛商品数">
                <template slot-scope="scope">
                  <el-form-item :prop="'price_step_list.'+scope.$index+'.threshold'" :rules="formRules.price_step_list.threshold">
                    <el-input :disabled="scope.$index === 0" v-model="scope.row.threshold" style="width: 100%" placeholder="请输入门槛商品数"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="众筹单价">
                <template slot-scope="scope">
                  <el-form-item :prop="'price_step_list.'+scope.$index+'.price'" :rules="formRules.price_step_list.price">
                    <el-input v-model="scope.row.price" placeholder="请输入众筹单价" style="width: 100%"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="!disabled" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.$index !== 0" type="text" @click="handleDeletePriceStep(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <div class="confirm-btn">
          <el-button size="medium" @click="handlerCallback">返回</el-button>
          <el-button size="medium" type="primary" @click="handlerSubmit" v-if="!disabled">保存</el-button>
        </div>
      </div>
    </div>
    <!--商品选择器-->
    <en-goods-sku-picker
      :sku="true"
      :limit="1"
      :show="dialogGoodsShow"
      :defaultData="skuIds"
      @confirm="handleGoodsPickerConfirm"
      @close="dialogGoodsShow = false"/>
  </div>
</template>

<script>
  import * as API_Crowdfunding from '@/api/crowdfunding'
  import { cloneObj } from '@/utils'
  import { GoodsSkuPicker } from '@/components'
  import { RegExp } from '~/ui-utils'

  export default {
    name: 'addCrowdfunding',
    components: {
      [GoodsSkuPicker.name]: GoodsSkuPicker
    },
    data() {
      return {
        form: {},
        skuIds: [],
        formRules: {
          name: [this.MixinRequired('请填写活动名称！')],
          timeRange: [this.MixinRequired('请选择活动时间！')],
          total_price: [
            this.MixinRequired('请填写活动金额！'),
            {
              validator: (rule, value, callback) => {
                if (!RegExp.money.test(value)) {
                  callback(new Error('请填写正确的金额！'))
                } else {
                  callback()
                }
              }
            }
          ],
          price_ratio: [
            this.MixinRequired('请填写众筹成功比例！'),
            {
              validator: (rule, value, callback) => {
                if (!RegExp.money.test(value)) {
                  callback(new Error('请填写正确的比例！'))
                } else {
                  callback()
                }
              }
            }
          ],
          price_step_list: {
            threshold: [
              this.MixinRequired('请填写门槛人数！'),
              {
                validator: (rule, value, callback) => {
                  if (!RegExp.positiveInteger.test(value)) {
                    callback(new Error('请填写正确的数量！'))
                  } else {
                    callback()
                  }
                }
              }
            ],
            price: [
              this.MixinRequired('请填写众筹价格！'),
              {
                validator: (rule, value, callback) => {
                  if (!RegExp.money.test(value)) {
                    callback(new Error('请填写正确的金额！'))
                  } else {
                    callback()
                  }
                }
              }
            ]
          }
        },
        disabled: false,
        goodsTableData: [],
        dialogGoodsShow: false
      }
    },
    watch: {
      $route: {
        handler(val) {
          if (val.name === 'viewCrowdfunding' || val.name === 'editCrowdfunding' || val.name === 'addCrowdfunding') {
            this.disabled = val.name === 'viewCrowdfunding'
            this.id = val.query.id

            if (val.name === 'addCrowdfunding') {
              this.form = {
                price_step_list: [{ threshold: 0, price: null }]
              }
              this.goodsTableData = []
              this.skuIds = []
            } else {
              this.getDetail()
            }
          }
        },
        immediate: true
      }
    },
    mounted() {
    },
    methods: {
      /** 获取规格列表 */
      getSkuList(val) {
        const _val = typeof val === 'string' ? JSON.parse(val) : val
        if (_val) {
          let _specs = []
          _val.forEach(elem => {
            _specs.push(elem.spec_value)
          })
          _specs = _specs.join('/')
          return _specs
        }
        return '/'
      },
      /** 保存商品选择器选择的商品 */
      handleGoodsPickerConfirm(val) {
        const _val = val
        this.goodsTableData = cloneObj(_val)
        this.form.sku_id = this.goodsTableData[0].sku_id
        this.skuIds = [this.form.sku_id]
      },
      /** 商品选择 */
      handlerSelectGoods() {
        this.dialogGoodsShow = true
      },
      /** 获取活动详情 */
      getDetail() {
        API_Crowdfunding.getDetail(this.id).then(res => {
          this.form = res
          this.form.timeRange = [parseInt(res.start_time) * 1000, parseInt(res.end_time) * 1000]
          this.goodsTableData = [res.goods_sku]
          this.skuIds = [res.sku_id]
        })
      },
      /** 保存提交 */
      handlerSubmit() {
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            const form = cloneObj(this.form)
            form.start_time = form.timeRange[0] / 1000
            form.end_time = form.timeRange[1] / 1000
            delete form.timeRange
            if (this.id) {
              // 修改
              API_Crowdfunding.edit(this.id, form).then(res => {
                this.$message.success('修改成功')
                this.$router.push({ name: 'crowdfunding' })
              })
            } else {
              // 新增
              API_Crowdfunding.add(form).then(res => {
                this.$message.success('保存成功')
                this.$router.push({ name: 'crowdfunding' })
              })
            }
          }
        })
      },
      handlerCallback() {
        this.$router.push({ name: 'crowdfunding' })
      },
      // 添加阶梯价格
      handleAddPriceStep() {
        this.form.price_step_list.push({
          threshold: null,
          price: null
        })
      },
      // 删除阶梯价格
      handleDeletePriceStep(index) {
        this.form.price_step_list.splice(index, 1)
      }
    }
  }
</script>
<style lang="scss" scoped>
.add-sign-in-wrap {
  .sign-in-container {
    background: #fff;
    margin-top: 20px;
    padding: 20px;
    display: flex;
    .bg-icon {
      width: 350px;
      height: 780px;
      margin: 0 30px
    }
    .goods-image{
      width:50px;
      height:50px;
    }
    .confirm-btn {
      text-align: center;
      padding-top: 10px;
      margin-top: 10px;
      border-top: 1px dashed #DCDFE6;
    }
    .form-box {
      width: 60%;
      font-size: 14px;
      font-weight: 700;
      color: #606266;
      padding: 0 30px;
      .btn-box {
        padding-left: 50px;
      }
      .text {
        width: 80px;
        text-align: center;
      }
      .el-input, .el-textarea {
        width: 400px;
      }
    }
    .item-border {
      border-bottom: 1px dashed #DCDFE6;
    }
    .sign-item {
      padding: 20px 0 20px 50px;
      display: flex;
      align-items: center;
      .rewards-item {
        display: flex;
        align-items: center;
        .el-select {
          width: 200px;
        }
        .el-input {
          width: 200px;
        }
        .right-item {
          margin-left: 20px;
          .gift {
            margin-bottom: 10px;
          }
        }
      }
      /deep/ .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      /deep/ .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;
      }
      .avatar {
        width: 80px;
        height: 80px;
        display: block;
      }

    }
    .point-box {
      padding: 10px 0 10px 0;
      border-bottom: 1px dashed #DCDFE6;
      .el-input {
        width: 200px;
      }
    }
  }
  .tips-info {
    font-size: 14px;
    background: #fff;
    color: #31708f;
    padding: 1px 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    li {
      line-height: 24px;
    }
  }
}
</style>
